package com.shop.shoppingmall.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.AlipayFundTransToaccountTransferModel;
import com.shop.shoppingmall.dao.ShDayCoinDao;
import com.shop.shoppingmall.dao.ShIntegralDao;
import com.shop.shoppingmall.dao.ShUserDao;
import com.shop.shoppingmall.dao.ShWalletDao;
import com.shop.shoppingmall.entity.ShRefundPrice;
import com.shop.shoppingmall.entity.ShUser;
import com.shop.shoppingmall.entity.ShWallet;
import com.shop.shoppingmall.service.ShDayCoinService;
import com.shop.shoppingmall.service.ShIntegralService;
import com.shop.shoppingmall.service.ShSpecialCoinService;
import com.shop.shoppingmall.service.ShWalletService;
import com.shop.shoppingmall.util.*;
import com.shop.shoppingmall.util.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 钱包账户(ShWallet)表服务实现类
 *
 * @author makejava
 * @since 2020-09-05 14:23:03
 */
@Service("shWalletService")
@Transactional
@Slf4j
public class ShWalletServiceImpl implements ShWalletService {
    @Resource
    private ShWalletDao shWalletDao;
    @Resource
    private ShUserDao shUserDao;
    @Resource
    private ShIntegralDao shIntegralDao;
    @Resource
    private ShDayCoinDao shDayCoinDao;
    @Resource
    private ShIntegralService shIntegralService;
    @Resource
    private ShDayCoinService shDayCoinService;
    @Resource
    private ShSpecialCoinService shSpecialCoinService;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ShWallet queryById(String id) {
        return this.shWalletDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param shWallet 实例对象
     * @return 实例对象
     */
    @Override
    public ShWallet insert(ShWallet shWallet) {
        this.shWalletDao.insert(shWallet);
        return shWallet;
    }

    /**
     * 修改数据
     *
     * @param shWallet 实例对象
     * @return 实例对象
     */
    @Override
    public ShWallet update(ShWallet shWallet) {
        this.shWalletDao.update(shWallet);
        return this.queryById(shWallet.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shWalletDao.deleteById(id) > 0;
    }

    /**
     * 用于注册时往钱包里添加一条记录
     * @param userId
     * @return
     */
    @Override
    public Result insertWallet(String userId) {
        String id = UUIDGenerator.generate();
        ShWallet shWallets = shWalletDao.selectByUserId(userId);
        if(shWallets != null){
            return Result.error("您的钱包已经开通！");
        }
        ShWallet shWallet = new ShWallet();
        shWallet.setId(id);
        shWallet.setUserId(userId);
        shWalletDao.insert(shWallet);
        return Result.ok("成功!");
    }

    @Override
    public Result updateIntegral(String userId, BigDecimal integral) {
        ShWallet shWallets = shWalletDao.selectByUserId(userId);
        if(shWallets != null){
            shWallets.setIntegral(shWallets.getIntegral().add(integral));
            shWalletDao.update(shWallets);
            return Result.ok("成功!");
        }else{
            return Result.error("未查询到该用户钱包信息");
        }
    }

    /**
     * 会员充值成功反馨天专用币
     * @param userId
     * @param SpecialCoin
     * @return
     */
    @Override
    public Result updateSpecialCoin(String userId, BigDecimal SpecialCoin) {
        ShWallet shWallets = shWalletDao.selectByUserId(userId);
        if(shWallets != null){
            shWallets.setSpecialCoin(shWallets.getSpecialCoin().add(SpecialCoin));
            shWalletDao.update(shWallets);
            shSpecialCoinService.insertSpecialCoin(SpecialCoin,userId,"会员充值反币");
            return Result.ok("成功!");
        }else{
            return Result.error("未查询到该用户钱包信息");
        }
    }

    /**
     * 设置支付密码
     * @param
     * @return
     */
    @Override
    public Result insertWalletOfPassword(String password, HttpServletRequest request) {
        //通过userId查询出用户名和用户表中的密码盐
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name);
        if(shUser == null || name == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        String salt = shUser.getSalt();
        //通过userId查询查询钱包的信息
        ShWallet shWallet = shWalletDao.selectByUserId(shUser.getId());
        if(shWallet.getPayPassword() != null){
            return Result.error("您已经设置过密码，请输入密码进行支付！");
        }
        String payPassword = PasswordUtil.encrypt(name, password, salt);
        ShWallet shWallets = new ShWallet();
        shWallets.setPayPassword(payPassword);
        shWalletDao.update(shWallet);
        return Result.ok("设置成功！");
    }

    /**
     * 兑换馨天币
     * @param
     * @return
     */
    @Override
    public Result updateWalletOfDayCoin(HttpServletRequest  request, Integer integral) {
        BigDecimal bigDecimal = new BigDecimal(integral);
        String name = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(name);
        if(shUser == null || name == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        //查询对应的钱包的信息
        ShWallet shWallet = shWalletDao.selectByUserId(shUser.getId());
        if(shWallet == null){
            return Result.error("暂时还没有对应的钱包信息！");
        }
        //拿到查出的钱包的积分
        BigDecimal dayCoin = shWallet.getIntegral();
        //拿到当前状态下的馨天币的数量
        BigDecimal coin = shWallet.getDayCoin();
        if(bigDecimal.compareTo(dayCoin) == 1){
            return Result.error("您输入的积分超过您当前拥有的积分，与实际不匹配，请重新输入！");
        }
        //用查出的积分和输入的积分进行判断，积分不足10000不能进行兑换
        if(dayCoin.compareTo(bigDecimal) == -1 || bigDecimal.compareTo(new BigDecimal(10000)) == -1){
            return Result.error("您的积分不足10000或您当前输入的积分数量与您钱包所拥有的的不匹配，不能进行兑换!");
        }
        //对输入要进行兑换的积分数量进行取余，如果大于零 说明有小数点
        BigDecimal[] decimals = bigDecimal.divideAndRemainder(BigDecimal.valueOf(10000));
        if(decimals[1].compareTo(new BigDecimal(0)) == 1){
            return Result.error("对不起，只能进行整数的馨天币兑换，请重新输入");
        }
        //用输入的积分除一万，求出兑换馨天币的数量
        BigDecimal divide = bigDecimal.divide(new BigDecimal(10000));
        //用查出的积分减去输入的积分求出剩余的积分
        shWallet.setIntegral(dayCoin.subtract(bigDecimal));
        shWallet.setDayCoin(coin.add(divide));
        shWalletDao.update(shWallet);

        //积分明细表里的积分明细
        shIntegralService.insertExpenditure(bigDecimal,shUser.getId(),"馨天币兑换");
        //馨天币表的明细
        shDayCoinService.insertShCoin(shUser.getId(),divide,"积分兑换");
        return Result.ok("兑换成功！");
    }

    /**
     * 根据用户id查询钱包的所有信息
     * @param
     * @return
     */
    @Override
    public Result selectWalletAll(HttpServletRequest request) {
        String nameByToken = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(nameByToken);
        if(shUser == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        ShWallet shWallet = shWalletDao.selectWalletAll(shUser.getId());
        if(shWallet == null){
            return Result.error("暂时没有钱包的有关信息");
        }
        return Result.ok(shWallet);
    }

    /**
     * 查询是否设置过支付密码
     * @param request
     * @return
     */
    @Override
    public Result selectShWalletPassWord(HttpServletRequest request) {
        String nameByToken = JwtUtil.getUserNameByToken(request);
        ShUser shUser = shUserDao.selectLoginName(nameByToken);
        if(shUser == null){
            return Result.error(CommonConstant.SC_OK_201,"您还未注册或者登录，请先注册或登录");
        }
        ShWallet shWallet = shWalletDao.selectWalletAll(shUser.getId());
        String payPassword = shWallet.getPayPassword();
        if(payPassword.equals("")){
            return Result.error(CommonConstant.SC_OK_301,"您还没有设置过支付密码");
        }
        return Result.error(CommonConstant.SC_OK_300,"支付密码已设置");
    }

    /**
     * 根据实体条件查询钱包的信息
     * @param map
     * @return
     */
    @Override
    public Result selectQueryWalletAll(Map map) {
        List<ShWallet> shWallets = shWalletDao.queryAll(map);
        if(shWallets == null){
            return Result.error("暂时还没有钱包的信息！");
        }
        return Result.ok(shWallets);
    }

    /**
     * 提现记录
     * @param password
     * @param request
     * @return
     */
    @Override
    public Result selectAll( HttpServletRequest request) {
        //解析token
        String name = JwtUtil.getUserNameByToken(request);
        if(name == null){
            return  Result.error("您还没有进行注册或者登录,请先注册登录！");
        }
        ShUser shUser = shUserDao.selectLoginName(name);
        String userId = shUser.getId();
        //查询钱包信息
        List<ShRefundPrice> shRefundPriceList = shWalletDao.selectAll(userId);
        return Result.ok(shRefundPriceList);
    }

//    @Override
//    public Result ailpay(ShUser shUser, ShRefundPrice shRefundPrice) {
//        shRefundPrice.setUserId(shUser.getId());
//        String salt = oConvertUtils.randomGen(16);
//        shRefundPrice.setAliNumber(salt);
//        shRefundPrice.setAliState("1");
//        shWalletDao.insertRefund(shRefundPrice);
//        if(shRefundPrice == null) {
//            return Result.error("提现订单生成错误");
//        }
//        String total_amount = shRefundPrice.getAliPrice();
//        AlipayFundTransToaccountTransferModel model = new AlipayFundTransToaccountTransferModel();
//        model.setOutBizNo(shRefundPrice.getAliNumber());//生成订单号
//        model.setPayeeType("ALIPAY_LOGONID");//固定值  ALIPAY_LOGON_ID  ALIPAY_LOGONID
//        model.setPayeeAccount(shRefundPrice.getAliPhone());//转账收款账户
//        model.setAmount(total_amount);
//        model.setPayeeRealName(shRefundPrice.getAliName());
//        model.setRemark("馨T网");
//        JSONObject jsonObject = transfer(model);
//        log.info("提现状态"+jsonObject.get("Success"));//成功 true 失败 false
//        if (jsonObject.get("Success").equals(true)){
//            ShRefundPrice shRefundPrice1 = shWalletDao.selectNumber(jsonObject.get("aliNumber").toString());
//            shRefundPrice1.setAliState("2");
//            shWalletDao.updateRefund(shRefundPrice1);
//            return Result.ok("提现成功");
//        }else{
//            return Result.error("提现失败");
//        }
//    }
}
